<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';

defineOptions({
  name: 'DraggableWidget'
});

const widgetRef = ref<HTMLElement>();
const isDragging = ref(false);
const dragOffset = ref({ x: 0, y: 0 });
const currentTime = ref('');
const weather = ref({ temp: '22°C', condition: '晴天' });
const signature = ref('今天也要开心游戏哦！🎮');
const showWidget = ref(true);

// 初始位置
let pos = { x: 20, y: 20 };
let rafId: number | null = null;
let pending = false;
let lastMoveEvent: MouseEvent | null = null;

const setWidgetPosition = (x: number, y: number) => {
  const widget = widgetRef.value;
  if (!widget) return;
  widget.style.left = `${x}px`;
  widget.style.top = `${y}px`;
};

const handleMouseMove = (e: MouseEvent) => {
  lastMoveEvent = e;
  if (!pending) {
    pending = true;
    rafId = requestAnimationFrame(() => {
      if (!isDragging.value || !widgetRef.value || !lastMoveEvent) return;
      const widget = widgetRef.value;
      const width = widget.offsetWidth;
      const height = widget.offsetHeight;
      const maxX = window.innerWidth - width;
      const maxY = window.innerHeight - height;
      let newX = lastMoveEvent.clientX - dragOffset.value.x;
      let newY = lastMoveEvent.clientY - dragOffset.value.y;
      newX = Math.max(0, Math.min(newX, maxX));
      newY = Math.max(0, Math.min(newY, maxY));
      pos = { x: newX, y: newY };
      setWidgetPosition(newX, newY);
      pending = false;
    });
  }
};

const handleMouseUp = () => {
  isDragging.value = false;
  document.body.style.userSelect = '';
  if (widgetRef.value) widgetRef.value.style.transition = '';
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  if (rafId) cancelAnimationFrame(rafId);
  pending = false;
};

const handleDragMouseDown = (e: MouseEvent) => {
  if (!widgetRef.value) return;
  isDragging.value = true;
  dragOffset.value = {
    x: e.clientX - pos.x,
    y: e.clientY - pos.y
  };
  document.body.style.userSelect = 'none';
  // 拖动时关闭 transition
  widgetRef.value.style.transition = 'none';
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

const toggleWidget = () => {
  showWidget.value = !showWidget.value;
};

const updateWeather = () => {
  const conditions = ['晴天', '多云', '小雨', '阴天'];
  const randomCondition = conditions[Math.floor(Math.random() * conditions.length)];
  const randomTemp = Math.floor(Math.random() * 20) + 15;
  weather.value = {
    temp: `${randomTemp}°C`,
    condition: randomCondition
  };
};

const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

let timeInterval: any;
let weatherInterval: any;

onMounted(() => {
  updateTime();
  updateWeather();
  timeInterval = setInterval(updateTime, 1000);
  weatherInterval = setInterval(updateWeather, 5 * 60 * 1000);
  // 初始定位
  setTimeout(() => setWidgetPosition(pos.x, pos.y), 0);
});

onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval);
  if (weatherInterval) clearInterval(weatherInterval);
  document.body.style.userSelect = '';
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  if (rafId) cancelAnimationFrame(rafId);
});
</script>

<template>
  <div
    v-if="showWidget"
    ref="widgetRef"
    class="draggable-widget"
    :class="{ dragging: isDragging }"
    style="position: fixed; z-index: 1000; left: 20px; top: 20px"
  >
    <!-- 拖动区 -->
    <div class="widget-drag-bar" @mousedown="handleDragMouseDown">
      <SvgIcon icon="mdi:drag" class="drag-icon" />
      <span class="drag-text">拖动</span>
    </div>
    <!-- 小挂件内容 -->
    <div class="widget-content">
      <!-- 时钟 -->
      <div class="widget-section">
        <div class="widget-icon">
          <SvgIcon icon="mdi:clock-outline" />
        </div>
        <div class="widget-text">
          <div class="time">{{ currentTime }}</div>
          <div class="label">当前时间</div>
        </div>
      </div>
      <!-- 天气 -->
      <div class="widget-section">
        <div class="widget-icon weather">
          <SvgIcon icon="mdi:weather-sunny" />
        </div>
        <div class="widget-text">
          <div class="temp">{{ weather.temp }}</div>
          <div class="label">{{ weather.condition }}</div>
        </div>
      </div>
      <!-- 个性签名 -->
      <div class="widget-section signature">
        <div class="widget-icon">
          <SvgIcon icon="mdi:format-quote-open" />
        </div>
        <div class="widget-text">
          <div class="quote">{{ signature }}</div>
        </div>
      </div>
    </div>
    <!-- 关闭按钮 -->
    <div class="widget-close" @click="toggleWidget">
      <SvgIcon icon="mdi:close" />
    </div>
  </div>
  <!-- 显示按钮 -->
  <div v-else class="widget-toggle" @click="toggleWidget">
    <SvgIcon icon="mdi:plus" />
  </div>
</template>

<style scoped>
.draggable-widget {
  position: fixed;
  z-index: 1000;
  width: 260px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.8));
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
  cursor: default;
  transition: all 0.3s ease;
  overflow: hidden;
}

.draggable-widget.dragging {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
}

.widget-drag-bar {
  width: 100%;
  height: 28px;
  display: flex;
  align-items: center;
  cursor: grab;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 13px;
  font-weight: 500;
  user-select: none;
  padding-left: 10px;
  letter-spacing: 1px;
}

.widget-drag-bar:active {
  cursor: grabbing;
}

.drag-icon {
  margin-right: 6px;
  font-size: 16px;
}

.widget-content {
  padding: 12px 16px 16px 16px;
  position: relative;
}

.widget-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 10px;
  transition: all 0.3s ease;
}

.widget-section:last-child {
  margin-bottom: 0;
}

.widget-icon {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-right: 8px;
  color: white;
  font-size: 14px;
}

.widget-icon.weather {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.widget-text {
  flex: 1;
}

.time,
.temp {
  font-size: 15px;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 2px;
}

.label {
  font-size: 11px;
  color: #718096;
}

.quote {
  font-size: 12px;
  color: #4a5568;
  font-style: italic;
  line-height: 1.4;
}

.signature {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.6));
}

.widget-close {
  position: absolute;
  top: 6px;
  right: 6px;
  width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  cursor: pointer;
  color: #718096;
  font-size: 13px;
  transition: all 0.3s ease;
}

.widget-close:hover {
  background: rgba(239, 68, 68, 0.1);
  color: #e53e3e;
  transform: scale(1.1);
}

.widget-toggle {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 44px;
  height: 44px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  font-size: 18px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  z-index: 1000;
}

.widget-toggle:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 25px rgba(102, 126, 234, 0.5);
}

@media (max-width: 768px) {
  .draggable-widget {
    width: 200px;
  }
  .widget-content {
    padding: 8px 8px 10px 8px;
  }
  .widget-section {
    padding: 6px;
    margin-bottom: 6px;
  }
  .widget-icon {
    width: 22px;
    height: 22px;
    font-size: 11px;
  }
  .time,
  .temp {
    font-size: 12px;
  }
  .quote {
    font-size: 11px;
  }
}
</style>
